package com.edu.hbwe.book.servlet.manager;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.edu.hbwe.book.service.ProductService;
import com.edu.hbwe.book.service.impl.ProductServiceImpl;


@WebServlet("/download")
public class DownloadServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String year = request.getParameter("year");
		String month = request.getParameter("month");
	
		//1,调用service
		 ProductService service=new ProductServiceImpl();
		//2,要查询下载的数据，已经支付的商品信息
		List<Object[]> ps = service.download(year,month);
		String fileName=year+"年"+month+"月销售榜单.csv";	
		//3.获取文件类型和响应头
		response.setContentType(this.getServletContext().getMimeType(fileName));
		//3.1设置下载框的响应头和防止文件中文乱码
		response.setHeader("Content-Disposition", "attachement;filename="+new String(fileName.getBytes("GBK"),"iso8859-1"));		
		response.setCharacterEncoding("gbk");	
		//3.2把查询出来的数据写到文件里面
		PrintWriter out = response.getWriter();
		out.println("商品名称,销售数量");
		for (int i = 0; i < ps.size(); i++) {
			Object[] arr=ps.get(i);
			out.println(arr[0]+","+arr[1]);			
		}
		out.flush();
		out.close();
	}
}
